package com.wecon.dianping.common;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Weikang  Wang
 * @program: com.wecon.dianping.common
 * @description: 全局异常处理
 * @date 2020/3/11 15:32
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 通用异常拦截器
     *
     * @param servletRequest  /
     * @param servletResponse /
     * @param e               /
     * @return /
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult doError(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Exception e) {
        if (e instanceof BusinessException) {
            return CommonResult.create(((BusinessException) e).getCommonError(), "fail");
        } else if (e instanceof NoHandlerFoundException) {
            CommonError commonError = new CommonError(EmBusinessError.NO_HANDLER_FOUND);
            return CommonResult.create(commonError, "fail");
        } else if (e instanceof ServletRequestBindingException) {
            CommonError commonError = new CommonError(EmBusinessError.BIND_EXCEPTION_ERROR);
            return CommonResult.create(commonError, "fail");
        } else {
            CommonError commonError = new CommonError(EmBusinessError.UNKNOWN_ERROR);
            return CommonResult.create(commonError, "fail");
        }
    }

}
